package dragon.social.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Leo
 * @Date: 2020/2/6 17:29
 */
@Controller
public class SecurityController {

    RequestCache requestCache = new HttpSessionRequestCache(); //springboot的工具，用于缓存请求

    RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); //springboot的工具，用于实现请求跳转

    Logger logger = LoggerFactory.getLogger(SecurityController.class);

    @RequestMapping("/login")
    public String test(){
        return "login1";
    }

    @RequestMapping("/logout")
    public String logout(Long userId){
        return "test";
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/signup")
    public String signup(){
        return "signup";
    }

    @RequestMapping("/errorpage")
    public String loginError(){
        return "errorpage";
    }

    @RequestMapping("/success")
    public String registerSuccess(){
        return "success";
    }

    /**
     * 需要身份认证时，跳转到这里来
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/authrequire")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)//设置状态码为未授权401
    public HttpServletResponse authenticationRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //保存引发身份认证跳转的请求
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if(savedRequest != null){
            //引发请求的url
            String redirectUrl = savedRequest.getRedirectUrl();
            logger.info("引发跳转的请求是：" + redirectUrl);
//            redirectStrategy.sendRedirect(request,response,"/login"); //此处直接跳转，就不走下面的代码了
//            if(StringUtils.endsWithIgnoreCase(redirectUrl,".html")){ //如果是.html结尾的网页引发的跳转
//                redirectStrategy.sendRedirect(request,response,"/login"); //此处直接跳转，就不走下面的代码了
//            }
        }
        response.sendRedirect("/login");
        return response;
    }
}
